package br.com.condominio.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.condominio.entity.Pessoa;

@Repository("pessoaDao")
public class PessoaDAO {

	private static final Log log = LogFactory.getLog(PessoaDAO.class);

	@PersistenceContext
	private EntityManager entityManager;
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Pessoa> findAll() {
		log.debug("findAll Pessoa instance");
		try {
			String jpql = "SELECT o FROM Pessoa o ORDER BY o.pessoNome";
			Query query = entityManager.createQuery(jpql);
			List<Pessoa> pessoas = (List<Pessoa>) query
					.getResultList();
			return pessoas;
		} catch (RuntimeException re) {
			log.error("findAll failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Pessoa> findByName(String string) {
		log.debug("findByName Pessoa instance");
		try {
			String jpql = " SELECT o from Pessoa o where o.pessoNome like :pessoNome order by o.pessoNome";
			Query query = entityManager.createQuery(jpql);
			query.setParameter("pessoNome", "%"+ string + "%");
			List<Pessoa> pessoas = (List<Pessoa>) query
					.getResultList();
			return pessoas;
		} catch (RuntimeException re) {
			log.error("findByName failed", re);
			throw re;
		}
	}

	@Transactional
	public Pessoa persist(Pessoa transientInstance) {
		log.debug("persisting Pessoa instance");
		try {
			entityManager.persist(transientInstance);
			log.debug("persist successful");
			return transientInstance;
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	@Transactional
	public void remove(Pessoa persistentInstance) {
		log.debug("removing Pessoa instance");
		try {
			persistentInstance = entityManager.find(Pessoa.class, persistentInstance.getPessoCodigo());
			entityManager.remove(persistentInstance);
			log.debug("remove successful");
		} catch (RuntimeException re) {
			log.error("remove failed", re);
			throw re;
		}
	}

	@Transactional
	public Pessoa merge(Pessoa detachedInstance) {
		log.debug("merging Pessoa instance");
		try {
			Pessoa result = entityManager.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}
	
	@Transactional
	public Pessoa findById(Integer id) {
		log.debug("getting Pessoa instance with id: " + id);
		try {
			Pessoa instance = entityManager.find(Pessoa.class, id);
			log.debug("get successful");
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
}
